package cn.itsource.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class ZuulFilterCloud extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String uri = request.getRequestURI();
        if (uri.endsWith("login") || uri.endsWith("regeix")){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String token = request.getHeader("token");
        if (token == null){
            HttpServletResponse response = currentContext.getResponse();
            try {
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write("没有登录，请登录");
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("没有登录");
            currentContext.setSendZuulResponse(false);
            return false;
        }
        return null;
    }
}
